﻿using System;
using System.Net;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Smith.AMC.Network;

namespace MemcachedClientTests
{
    [TestClass]
    public class SocketQueueTest
    {
        [TestMethod]
        public void TestMethod1()
        {
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11211);
            ManualResetEvent evt = new ManualResetEvent(false);
            
            SocketQueue sq = new SocketQueue(new List<ClientSocket>
            {
                new ClientSocket(ep, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp),
                new ClientSocket(ep, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp)
            });

            long aquires = 0;
            long tries = 0;

            for (int i = 0; i < 50; i++)
            {
                Thread t = new Thread(obj =>
                {
                    do
                    {
                        IClientSocket socket;
                        bool dequeued = sq.Dequeue(out socket);
                        Interlocked.Increment(ref tries);
                        if (dequeued)
                        {
                            Interlocked.Increment(ref aquires);
                            sq.Enqueue(socket);
                        }
                    } while (!evt.WaitOne(1, false));
                    Console.WriteLine("Thread {0} quit",Thread.CurrentThread.Name);
                })
                {
                    Name="Thread"+i
                };

                t.Start();
            }

            Thread.Sleep(10000);
            evt.Set();
            Console.WriteLine("Tries:{0}", tries);
            Console.WriteLine("Aquires:{0}",aquires);
        }
    }
}
